<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card class="box-card">
      <!-- 搜索框 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="clearSearch">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addUserClick">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="userlist" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色名"></el-table-column>
        <el-table-column label="状态">
          <template v-slot:default="scope">
            <el-switch v-model="scope.row.mg_state" @change="changeUserStatus(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template v-slot:default="editscope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editUser(editscope.row.id)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="delUserById(editscope.row.id)"
            ></el-button>
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="atributeRoles(editscope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <add-user :visible.sync="addDialogVisible" @addUserForForm="getUserList()"></add-user>
    <edit-user
      :visible.sync="editDialogVisible"
      @updateUsers="getUserList()"
      :edituserinfo="edituserinfo"
    ></edit-user>
    <role-change
      :visible.sync="rolesDialogVisible"
      :changeuserinfo="userInfo"
      @changeSuccess="getUserList()"
    ></role-change>
  </div>
</template>
<script>
import AddUser from '../../components/users/AddUser'
import EditUser from '../../components/users/EditUser'
import RoleChange from '../../components/users/RoleChange'
export default {
  components: {
    AddUser,
    EditUser,
    RoleChange
  },
  data() {
    return {
      // 获取用户数据的参数
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      userlist: [],
      total: 0,
      addDialogVisible: false,
      editDialogVisible: false,
      edituserinfo: {},
      rolesDialogVisible: false,
      userInfo: {},
      // rolesList: [],
      // 已选中的id值
      selectedRoleId: ''
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    // 获取用户列表数据
    async getUserList() {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) {
        return this.$message.error('用户列表数据获取失败')
      }
      this.userlist = res.data.users
      this.total = res.data.total
    },
    addUserClick() {
      this.addDialogVisible = true
    },
    // 修改每页展示的数据条数
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    // 修改页码
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    // 更新用户状态
    async changeUserStatus(userinfo) {
      const { data: res } = await this.$http.put(
        `users/${userinfo.id}/state/${userinfo.mg_state}`
      )
      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state
        return this.$message.error('更新用户状态失败！')
      }
      this.$message.success('更新用户状态成功')
    },
    // 清空搜索输入框后重新渲染数据
    clearSearch() {
      this.getUserList()
    },
    // 修改用户
    async editUser(id, type) {
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户信息失败')
      }
      this.edituserinfo = res.data
      this.editDialogVisible = true
    },
    async delUserById(id) {
      const resultConfirm = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      /*
       * 确认框使用前需在element.js中引用并定义$confirm
       * 确认后返回值为confirm
       * 取消后返回值为cancel
       * 注意：取消状态要用.catch来接收错误状态，否则会报错
       * 因为返回值是一个promise类型，所以用async和await搭配使用
       */
      if (resultConfirm === 'cancel') {
        return this.$message.info('取消了删除的动作')
      }
      const { data: res } = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除用户失败')
      }
      this.$message.success('删除用户成功')
      this.queryInfo.pagenum = 1
      this.queryInfo.pagesize = 2
      this.getUserList()
    },
    // 点击分配角色的按钮
    async atributeRoles(userinfo) {
      this.userInfo = userinfo
      this.rolesDialogVisible = true
    }
  }
}
</script>
<style lang="less" scoped>
</style>
